<?php

namespace admin\controllers;

use Yii;
use admin\models\Order;
use admin\models\AdminUser;
use common\helpers\Hui;
use common\helpers\Html;

class OrderController extends \admin\components\Controller
{
    /**
     * @authname 订单列表
     */
    public function actionList()
    {
        $query = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.admin'])->manager()->orderBy('order.id DESC');
        $countQuery = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.admin'])->manager();

        // 今日盈亏统计，交易额、手数
        $profit = $countQuery->andWhere(['order.order_state' => Order::ORDER_THROW])->select('SUM(order.profit) profit')->one()->profit ?: 0 ;
        $amount = $countQuery->select('SUM(order.deposit) deposit')->one()->deposit ?: 0;
        $hand = $countQuery->select('SUM(order.hand) hand')->one()->hand ?: 0;
        $fee = $countQuery->select('SUM(order.fee) fee')->one()->fee ? : 0;

        $html = $query->getTable([
            'user.id',
            'user.nickname',
            'parent.nickname' => ['header' => '推荐人昵称'],
            'admin.id' => ['header' => '居间商', 'value' => function ($row) {
                if (!isset($row->user->admin->power)) {
                    return '';
                }
                return $row->user->admin->power == AdminUser::POWER_RING ? $row->user->admin->username : '无';
            }],
            'admin.username' => ['header' => '经济会员', 'value' => function ($row) {
                if (!isset($row->user->admin->power)) {
                    return '';
                }
                if ($row->user->admin->power == AdminUser::POWER_MEMBER) {
                    return $row->user->admin->username;
                } else {
                    return AdminUser::findOne($row->user->admin->pid)->username;
                }
            }],
            'product.name',
            'created_at',
            'updated_at' => function ($row) {
                return $row['order_state'] == Order::ORDER_POSITION ? '' : $row['updated_at'];
            },
            'trade_type' => ['header' => '交易时间', 'value' => function ($row) {
                return intval($row->stop_profit_point) . "M";
            }],
            'rise_fall' => ['header' => '涨跌', 'value' => function ($row) {
                return $row['rise_fall'] == Order::RISE ? Html::redSpan('买涨') : Html::greenSpan('买跌');
            }],
            'price',
            'sell_price' => function ($row) {
                if ($row['order_state'] == Order::ORDER_POSITION) {
                    return '';
                } else {
                    if ($row['price'] < $row['sell_price']) {
                        return Html::redSpan($row['sell_price']);
                    } else {
                        return Html::greenSpan($row['sell_price']);
                    }
                }
            },
            'fee',
            'deposit',
            'profit' => function ($row) {
                return $row['profit'] >= 0 ? Html::redSpan($row['profit']) : Html::greenSpan($row['profit']);
            },
            'order_state',
            u()->power < AdminUser::POWER_ADMIN?:['header' => '操作', 'width' => '60px', 'value' => function ($row) {
                if ($row->sign_state == Order::SIGN_NO) {
                    $text = '未标记';
                } else {
                    $text = $row->sign_state == Order::SIGN_WIN ? '标记盈' : '标记亏';
                }
                if ($row->order_state == Order::ORDER_POSITION) {
                    return Hui::primaryBtn($text, ['editSign', 'id' => $row->id], ['class' => 'signBtn']);
                }
                return $text;
            }]
            // ['type' => [], 'value' => function ($row) {
            //     return $row['order_state'] == Order::ORDER_POSITION ? Hui::warningBtn('平仓', ['order/sellOrder', 'id' => $row['id']], ['class' => 'sellOrderBtn']) : '';
            // }]
        ], [
            'ajaxReturn' => [
                'countProfit' => '盈亏统计：' . ($profit >= 0 ? Html::redSpan($profit) : Html::greenSpan($profit)) . '，',
                'countAmount' => $amount,
                'countHand' => $hand,
                'countFee' => $fee
            ],
            'searchColumns' => [
                'user.id' => ['header' => '用户id'],
                // 'user.pid' => ['header' => '推荐人id'],
                'parent.nickname' => ['header' => '推荐人昵称'],
                'ringname' => ['header' => '居间商'],
                'membername' => ['header' => '经济会员'],
                'product_name' => ['type' => 'select', 'header' => '选择产品'],
                'user.nickname' => ['header' => '昵称'],
                'user.mobile',
                'time' => 'timeRange',
                'is_profit' => ['type' => 'select', 'header' => '是否盈亏'],
                'order_state' => 'select'
            ]
        ]);

        return $this->render('list', compact('html', 'profit', 'amount', 'hand', 'fee'));
    }

    /**
     * @authname 手动平仓
     */
    public function actionSellOrder()
    {
        $id = get('id');

        if (Order::sellOrder($id)) {
            return success('成功平仓');
        } else {
            return error('此单已平');
        }
    }

    /**
     * @authname 手动标记风控
     */
    public function actionEditSign()
    {
        $id = get('id');
        $order = Order::findOne($id);
        if (!empty($order)) {
            switch (post('sign')) {
                case '1':
                    $order->sign_state = Order::SIGN_WIN;
                    break;

                case '2':
                    $order->sign_state = Order::SIGN_FAIL;
                    break;

                case '3':
                    $order->sign_state = Order::SIGN_NO;
                    break;

                default:
                    return error('请输入盈、亏、取消中的三种，不要输入其它内容！');
                    break;
            }
            $order->update();
            return success('修改成功!');
        } else {
            return error('数据非法');
        }
    }
    public function actionCurrentList()
    {
        $map = ['order.order_state' => Order::ORDER_POSITION];
        $query = (new Order)->listQuery()->joinWith(['product.dataAll', 'user.parent', 'user.admin'])->manager()->filterWhere($map)->orderBy('order.id DESC');

        $html = $query->getTable([
            'user.id',
            'user.nickname',
            ['header' => '推荐人(ID)', 'value' => function ($row) {
                return $row->user->getParentLink('user.id');
            }],
            'admin.username' => ['header' => '代理商账户'],
            'product.name',
            'created_at',
            'updated_at' => function ($row) {
                return $row['order_state'] == Order::ORDER_POSITION ? '' : $row['updated_at'];
            },
            'rise_fall' => ['header' => '涨跌', 'value' => function ($row) {
                return $row['rise_fall'] == Order::RISE ? Html::redSpan('买涨') : Html::greenSpan('买跌');
            }],
            'price',
            'fee',
            'sell_price' => function ($row) {
                if ($row['order_state'] == Order::ORDER_POSITION) {
                    return '';
                } else {
                    if ($row['price'] < $row['sell_price']) {
                        return Html::redSpan($row['sell_price']);
                    } else {
                        return Html::greenSpan($row['sell_price']);
                    }
                }
            },
            'hand',
            'deposit',
            'profit' => function ($row) {
                return $row['profit'] >= 0 ? Html::redSpan($row['profit']) : Html::greenSpan($row['profit']);
            },
            'user.account',
            'order_state'
        ]);

        return $html;
    }
}
